Do you expect that a modern electronic calculator will give you the same answer as Java for the expression  (31.5 - 12)/4.1 ?

Answer:

Yes. The meaning of operators and parentheses is about the same in electronic calculators and in Java. But Java does integer and floating point math, and sometimes this can make a difference.

Weird Integer Arithmetic

The division operator / means integer division if there is an integer on both sides of it. If one or two sides has a floating point number, then it means floating point division. The result of integer division is always an integer; if the exact result calls for a decimal fraction, that part of the result is dropped (not rounded).

There is a difference between what Java will do and what a calculator will do. A calculator will do floating point arithmetic for the expression:

7/2

Java will regard this as integer arithmetic and give you:

7/2 = 3

This is easy enough to see when it is by itself, but here is a more confusing case of the same thing:

1.5 + 7/2

The division will be done first, because / has higher precedence than +. The result, 3, is an integer. Now floating point 1.5 is added to integer 3 to get floating point 4.5.

Integer arithmetic may be used in parts of an expression and not in others, even though the final value of the expression is floating point. Most programming languages do this. Believe it or not, it is fortunate that Java works this way. It would be awful if what was done in the middle of a calculation depended on the final result.

QUESTION 5:

What is the result of evaluating the following expression:

1/2 + 1/2